<template>
  <div class="app-container">
    <el-form ref="formRef" :model="form" :rules="rules">
      <el-row class="el-top">
        <el-col :span="4">
          <el-form-item class="ml20 mt8 mr20" label="入库方式:" prop="importClass">
            <el-select v-model="form.importClass" :disabled="!isImport" placeholder="请选择入库方式"
                       @change="importClassClick">
              <el-option v-for="(dict, index) in typeList" :key="dict.dictValue" :label="dict.dictLabel"
                         v-show="dict.dictValue !='12'"
                         :value="dict.dictValue"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item v-if="form.importClass === '0'" class="mt8" label="供货单位:" prop="supplier">
            <supplier :id="form.supplier" ref="firmName" :placeholder="'请选择供货单位'"
                      style="float: left; width: 180px"
                      @supplierChange="supplierChange"/>
          </el-form-item>
          <el-form-item v-else class="mt8" label="供货单位:" prop="storageFrom">
            <drug-storage-info ref="drugStorageDeptRef" :drug-fromLevel-str="drugFromLevelStr"
                               :org-id="queryParams.orgId"
                               :value="form.storageFrom" :value-storage-id="form.storageFrom"
                               class="import-master" style="width: 180px"
                               @drugStorageChange="storageFromClick"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item class="ml20 mt8" label="入库科室:" prop="storageId">
            <drug-storage-dept ref="storageIdDeptRef" :org-id="queryParams.orgId"
                               :value-storage-id="form.storageId" disabled="disabled" style="width: 180px"
                               class="import-master" @drugStorageChange="storageIdClick"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item class="ml20 mt8" label="付款方式:">
            <el-select v-model="form.accountType" clearable placeholder="请选择付款方式" style="width: 50%">
              <el-option v-for="dict in dictDataMap['drug_payment_type']" :key="dict.dictValue"
                         :label="dict.dictLabel"
                         :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <span class="el-form-item__label ml10 mt5">进价合计：<span class="fz19 font-color-red mr5"> {{
            tradePriceTotal
          }}</span>元</span>
        <span class="el-form-item__label ml10 mt5">售价合计：<span class="fz19 font-color-red mr5"> {{
            retailPriceTotal
          }}</span>元</span>
      </el-row>
      <el-row>
        <!-- 入库编辑列表 -->
        <el-table :border="true" :data="form.detailList" :header-cell-style="$headerCellStyle"
                  header-cell-class-name="requiredClass">
          <el-table-column :align="'center'" fixed="left" label="药品名称" min-width="168px" prop="drugName">
            <template #default="scope">
              <el-form-item :prop="'detailList.' + scope.$index + '.itemInfo'" :rules="rules.itemInfo"
                            class="table-form-margin">
                <!-- 入库药品检索 -->
                <el-input v-if="scope.row.isShow" v-model="scope.row.drugName"
                          @focus="isShowItemNameFocus(scope.$index, scope.row)">
                </el-input>
                <automatic-completion v-else ref="itemAutomatic" :dict-array="dictArray"
                                      :table-body-list="tableBodyList"
                                      :table-head-list="tableHeadList" :title="itemTitle"
                                      :right-div-show-type="'drugImportAndExport'" :width="1000" style="width: 100%"
                                      @itemNameInput="itemNameInput" @rowClick="rowClick($event, 0)"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="进货价" prop="tradePrice"
                           width="100px">
            <template #default="scope">
              <el-form-item :prop="'detailList.' + scope.$index + '.tradePrice'" :rules="rules.tradePrice"
                            class="table-form-margin">
                <el-input v-model="scope.row.tradePriceShow"
                          @blur="tradePriceBlue(scope.$index)"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="比例" prop="discount"
                           width="90px">
            <template #default="scope">
              <el-form-item :prop="'detailList.' + scope.$index + '.discount'" :rules="rules.discount"
                            class="table-form-margin">
                <el-select ref="ratio" v-model="scope.row.discount" filterable placeholder="请选择比例"
                           style="width: 100%"
                           @change="tradePriceBlue(scope.$index)">
                  <el-option v-for="dict in dictDataMap['price_ratio']" :key="dict.dictValue"
                             :label="dict.dictLabel"
                             :value="dict.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="零售价" prop="retailPrice"
                           width="100px">
            <template #default="scope">
              <el-form-item :prop="'detailList.' + scope.$index + '.retailPrice'"
                            :rules="rules.retailPrice"
                            class="table-form-margin">
                <el-input v-model="scope.row.retailPriceShow"
                          @blur="tradePriceBlue(scope.$index)"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="批号" prop="batchNo"
                           width="110px">
            <template #default="scope">
              <el-form-item :prop="'detailList.' + scope.$index + '.batchNo'" :rules="rules.batchNo"
                            class="table-form-margin">
                <el-input v-model="scope.row.batchNo"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="入库数量" prop="quantity"
                           width="130px">
            <template #default="scope">
              <el-form-item :prop="'detailList.' + scope.$index + '.quantity'" :rules="rules.quantity"
                            class="table-form-margin">
                <el-input v-model="scope.row.quantity" clearable>
                  <template #append>
                    <dict-data-tag :options="dictDataMap['spec_unit']"
                                   :value="scope.row.currentUnits"/>
                  </template>
                </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="生产日期" prop="produceDate"
                           width="135px">
            <template #default="scope">
              <el-form-item :prop="'detailList.' + scope.$index + '.produceDate'"
                            :rules="rules.produceDate">
                <el-date-picker v-model="scope.row.produceDate" :disabled-date="disabledProduceDateFunc" clearable
                                placeholder="生产日期" style="width: 100%" type="date"
                                value-format="YYYY-MM-DD"
                                @change="produceDateChange(scope.$index)">
                </el-date-picker>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="有效期" prop="expireDate"
                           width="135px">
            <template #default="scope">
              <el-form-item :prop="'detailList.' + scope.$index + '.expireDate'"
                            :rules="rules.expireDate">
                <el-date-picker v-model="scope.row.expireDate" clearable placeholder="有效期"
                                style="width: 100%"
                                type="date" value-format="YYYY-MM-DD"
                                @change="expireDateChange(scope.$index)">
                </el-date-picker>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="货柜" prop="location"
                           width="100px">
            <template #default="scope">
              <el-form-item class="table-form-margin">
                <el-input v-model="scope.row.location"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="厂家" prop="firmName"
                           width="160px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="药品编码" prop="drugCode"
                           width="120px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="规格" prop="currentSpec"
                           width="100px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="包装数量" prop="packageNum"
                           width="100px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" fixed="right" label="追溯码"
                           prop="trackCodes"
                           width="85px">
            <template #default="scope">
              <el-popover
                :width="200"
                placement="left"
                title="追溯码详情"
                trigger="hover"
              >
                <template #reference>
                  <el-button v-if="scope.row.drugName" round type="warning"
                             @click="trackCodesEnter(scope.row,scope.$index)">录入
                  </el-button>
                </template>
                <template v-if="scope.row.trackCodes">
                  <template v-for="item in scope.row.trackCodes.split(';')">
                    <div style="border-bottom: #9a9a9a 1px dotted">{{ item }}</div>
                  </template>
                  共计录入：<span
                  class="ys-css">{{ (scope.row.trackCodes ? scope.row.trackCodes.split(";").length : 0) - 1 }}</span>条追溯码
                </template>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" class-name="small-padding fixed-width" fixed="right" header-align="center"
                           label="操作"
                           width="60px">
            <template #default="scope">
              <el-tooltip class="item" content="添加" effect="dark" placement="top">
                <el-button circle type="primary" @click="handleAdd(scope.row)">
                  <template #icon>
                    <i-ep-plus/>
                  </template>

                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

      </el-row>
      <el-row class="mt5">
        <el-col :span="1.5" class="mr10">
          <span class="mr20">待入库药品</span>
          <el-button style="margin-bottom: 3px" type="primary" @click="temporaryStorage">
            <template #icon>
              <i-ep-FolderOpened/>
            </template>
            暂存
          </el-button>
        </el-col>
        <el-col :span="1.5" class="mr10">
          <el-button :disabled="buttonLoading" type="info" @click="temporaryStorageTableClick">
            <template #icon>
              <i-ep-memo/>
            </template>
            暂存列表
          </el-button>
        </el-col>
        <el-col :span="2" class="mr10">
          <el-button :disabled="buttonLoading" type="success" @click="lastSave">
            <template #icon>
              <i-ep-FolderOpened/>
            </template>
            确认入库
          </el-button>
        </el-col>
        <el-col :span="8">
          <span style="color: #fd0101;font-size: 13px">入库发票号：</span>
          <el-input v-model="form.invoiceNo" clearable style="width: 180px"/>
        </el-col>
        <el-table v-adaptive="120" :border="true" :data="form.detailListSave" :header-cell-style="$headerCellStyle"
                  highlight-current-row>
          <el-table-column :align="'center'" fixed="left" label="序号" prop="index" width="100px">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :align="'center'" fixed="left" label="药品名称" min-width="168px" prop="drugName"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="进货价" prop="tradePrice"
                           width="100px">
            <template #default="scope">
              {{ scope.row.tradePriceShow }}
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="比例" prop="discount"
                           width="100px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="零售价" prop="retailPrice"
                           width="100px">
            <template #default="scope">
              {{ scope.row.retailPriceShow }}
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="批号" prop="batchNo"
                           width="120px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="入库数量" prop="quantity"
                           width="90px">
            <template #default="scope">
              <div>
                <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.currentUnits"
                               class="mb-10 mr10"
                               style="float: right"/>
                <div class="mr20" style="float: right; font-weight: bold">
                  {{ scope.row.quantity }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="生产日期" prop="produceDate"
                           width="140px">
            <template #default="scope">
              <span>{{ $parseTime(scope.row.produceDate, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="有效期" prop="expireDate"
                           width="140px">
            <template #default="scope">
              <span>{{ $parseTime(scope.row.expireDate, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="货柜" prop="location"
                           width="100px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="厂家" prop="firmName"
                           width="160px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="药品编码" prop="drugCode"
                           width="120px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="规格" prop="currentSpec"
                           width="100px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="包装数量" prop="packageNum"
                           width="80px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" fixed="right" label="追溯码"
                           prop="trackCodes"
                           width="130px">
            <template #default="scope">
              <el-popover
                :width="200"
                placement="left"
                title="追溯码详情"
                trigger="hover"
              >
                <template #reference>
                  <el-button v-if="scope.row.drugName" round
                             type="warning">详情
                  </el-button>
                </template>
                <template v-if="scope.row.trackCodes">
                  <template v-for="item in scope.row.trackCodes.split(';')">
                    <div style="border-bottom: #9a9a9a 1px dotted">{{ item }}</div>
                  </template>
                </template>
                共计录入：<span
                class="ys-css">{{ (scope.row.trackCodes ? scope.row.trackCodes.split(";").length : 0) - 1 }}</span>条追溯码
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" class-name="small-padding fixed-width" fixed="right" header-align="center"
                           label="操作"
                           width="90px">
            <template #default="scope">
              <el-tooltip class="item" content="编辑" effect="dark" placement="left">
                <el-button v-hasPerm="['base:drugImportMaster:edit']" circle type="success"
                           @click="handleUpdate(scope.row, scope.$index)">
                  <template #icon>
                    <i-ep-edit/>
                  </template>

                </el-button>
              </el-tooltip>
              <el-tooltip class="item" content="删除" effect="dark" placement="top">
                <el-button v-hasPerm="['base:drugImportMaster:remove']" circle type="danger"
                           @click="handleDelete(scope.row, scope.$index)">
                  <template #icon>
                    <i-ep-delete/>
                  </template>

                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
    </el-form>
    <el-dialog v-model="open" :close-on-click-modal="false" :title="'暂存列表'" append-to-body width="94%"
               @close="temporaryStorageClose">
      <el-row :gutter="10">
        <el-col :span="10">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>入库主记录（点击列表可查看入库药品明细）</span>
            </div>
            <div class="mb20">
              <el-table :border="true" :data="stagingList" :header-cell-style="$headerCellStyle" height="400"
                        @row-click="stagingMaster">
                <el-table-column :align="'center'" class-name="small-padding fixed-width" fixed="left"
                                 header-align="center" label="操作" width="80px">
                  <template #default="scope">
                    <el-tooltip class="item" content="引入"
                                effect="dark"
                                placement="top">
                      <el-button circle type="primary" @click.stop="bringIn(scope.row)">
                        <template #icon>
                          <i-ep-edit/>
                        </template>
                      </el-button>
                    </el-tooltip>
                    <el-tooltip class="item" content="删除"
                                effect="dark"
                                placement="top">
                      <el-button circle type="danger" @click.stop="deleteMaster(scope.row)">
                        <template #icon>
                          <i-ep-delete/>
                        </template>
                      </el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="采购商"
                                 prop="supplierName"/>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="出库库房"
                                 prop="storageFromName"/>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="入库库房"
                                 prop="storageName"/>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="入库方式"
                                 min-width="75px"
                                 prop="importClass">
                  <template #default="scope">
                    <dict-data-tag :options="dictDataMap['drug_storage_type']"
                                   :value="scope.row.importClass"/>
                  </template>
                </el-table-column>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="入库时间"
                                 min-width="130px"
                                 prop="importDate"/>
                <el-table-column :align="'left'" :show-overflow-tooltip="true" label="应付款(总价)"
                                 min-width="90px"
                                 prop="accountReceivable"/>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="操作人"
                                 min-width="90px"
                                 prop="createByName">
                </el-table-column>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="操作时间"
                                 min-width="90px"
                                 prop="createTime">
                </el-table-column>
              </el-table>
              <pagination v-show="total > 0" v-model:limit="queryParams.pageSize"
                          v-model:page="queryParams.pageNum"
                          :total="total" @pagination="getList"/>
            </div>
          </el-card>
        </el-col>
        <el-col :span="14">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>入库单明细</span>
            </div>
            <div class="mb20">
              <el-table :border="true" :data="stagingListDetail" :header-cell-style="$headerCellStyle" height="400">
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="序号"
                                 min-width="60px"
                                 prop="itemNo"/>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="药品编号"
                                 min-width="100px"
                                 prop="drugCode"/>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="药品名称"
                                 min-width="180px"
                                 prop="drugName">
                  <template #default="scope">
                    <span class="fz14 fw-bold">{{ scope.row.drugName }}</span>
                  </template>
                </el-table-column>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="包装数量"
                                 min-width="90px"
                                 prop="packageNum"/>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="包装规格"
                                 min-width="120px"
                                 prop="packageSpec"/>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="入库数量"
                                 min-width="90px"
                                 prop="quantity">
                  <template #default="scope">
                    <div>
                      <dict-data-tag :options="dictDataMap['spec_unit']"
                                     :value="scope.row.packSize === '1' ? scope.row.minUnits :scope.row.packageUnits"
                                     class="mb-10 mr10" style="float: right"/>
                      <div class="mr20" style="float: right; font-weight: bold">
                        {{ scope.row.quantity }}
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="进货价"
                                 min-width="90px"
                                 prop="tradePriceShow"/>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="零售价"
                                 min-width="90px"
                                 prop="retailPriceShow"/>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="生产批号"
                                 min-width="90px"
                                 prop="batchNo"/>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="生产日期"
                                 min-width="90px"
                                 prop="produceDate">
                  <template #default="scope">
                    <span>{{ $parseTime(scope.row.produceDate, "{y}-{m}-{d}") }}</span>
                  </template>
                </el-table-column>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="有效期"
                                 min-width="90px"
                                 prop="expireDate">
                  <template #default="scope">
                    <span>{{ $parseTime(scope.row.expireDate, "{y}-{m}-{d}") }}</span>
                  </template>
                </el-table-column>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="追溯码"
                                 min-width="90px"
                                 prop="trackCodes">
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-dialog>

    <el-dialog
      v-model="trackCodesEnterOpen"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      title=""
      width="400px"
      @close="trackCodesCancel"
    >
      <template #header>
        <div class="ml20 fz15" style="color: #00c0ef;margin-bottom: -20px !important">
          <div>追溯码录入</div>
          <span class="mr20"
                style="font-size: 16px;font-weight: bold;color: #484848">药品名：{{ trackCodesRow.drugName }}</span>
          <div class="mr20"
               style="font-size: 16px;font-weight: bold;color: #484848">厂家：{{ trackCodesRow.firmName }}
          </div>
          <span style="color: #ea0a0a">每条录入完成后,按【回车】输入下一条</span>
        </div>
      </template>
      <el-input
        v-model="trackCodesInput"
        :rows="20"
        placeholder="请输入或扫描追溯码"
        style="width: 100%"
        type="textarea"
        @keydown.enter.native="lineFeed"
      />
      <div>
        共计录入：<span class="ys-css">{{ trackCodesInput ? trackCodesInput.split(";").length - 1 : 0 }}</span>条追溯码
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="trackCodesCancel">取消</el-button>
          <el-button type="primary" @click="trackCodesOk">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {
  addDrugImportMaster,
  delDrugImportMaster,
  getAutoDrugPriceInfo,
  selectPageDrugImportMaster,
} from "@/api/drug/drugImportMaster";
import {getStoreroomDistinguish} from "@/api/drug/drugInoutClass";
import {listDrugImportDetail} from "@/api/drug/drugImportDetail";
import {quantityNumber, retailPriceV, tradePriceV} from "@/utils/myRules";
import {useUserStoreHook} from "@/store/modules/user";
import {useDictStoreHook} from "@/store/modules/dict";
import {drugImporOrList, jsonStrInObj} from "@/utils/autoComplete";
import {useRouter} from 'vue-router';

const router = useRouter()
const formRef = ref();
const storageIdDeptRef = ref();
const drugStorageDeptRef = ref();
const useUserStore = useUserStoreHook();
const {proxy} = getCurrentInstance() as any;
const dictStore = useDictStoreHook();
const dictDataMap = ref(
  dictStore.isTypeGetData("drug_storage_type", "drug_payment_type", "price_ratio", "spec_unit")
);
const currentSelectDept = proxy.$currentSelectDept
// 科室等级字符串
const drugFromLevelStr = ref<String>('')
// 按钮loading
const buttonLoading = ref(false);
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
// 追溯码弹出框是否打开
const trackCodesEnterOpen = ref(false);
// 追溯码弹列表数据
const trackCodesRow = ref<any>({});
// 追溯码弹出框input内容
const trackCodesInput = ref<String>("")
// 追溯码点击行号
const currentIndex = ref(-1)
const itemAutomatic = ref();
// 暂存列表
const stagingList = ref<any>([]);
// 暂存入库明细列表
const stagingListDetail = ref<any>([]);
// 判断是否可入库
const isImport = ref(true);
// 总条数
const total = ref(0);
// 是否显示暂存列表弹出层
const open = ref(false);
// 入库方式list
const typeList = ref<any>([]);
// 表单参数
const form = ref<any>({
  importClass: "",
  isStaging: "Y",
  accountType: "1",
  supplier: "",
  storageFrom: "",
  invoiceNo: "",
  detailList: [
    {
      expireDate: "",
      discount: "1",
      itemInfo: "",
      infoId: "",
      drugName: "",
      drugCode: "",
      orgId: "",
      packageSpec: "",
      packageUnits: "",
      tradePrice: "",
      retailPrice: "",
      firmId: "",
      firmName: "",
      packageNum: "",
      drugPriceId: "",
      trackCodes: ""
    },
  ],
  detailListSave: [],
});
// 暂存列表查询参数
const detailQuery = ref<any>({
  pageNum: 1,
  pageSize: 10,
  masterId: "",
});
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  orgId: undefined,
});
// 项目选择自动补全窗体名称
const itemTitle = ref("药品选择");
// 项目选择自动补全表格表头
const tableHeadList = ref<any>(jsonStrInObj(drugImporOrList));
// 项目选择自动补全表格数据
const tableBodyList = ref<any>([]);
// 项目选择自动补全字典数组
const dictArray = ref(["spec_unit"]);
// 进价合计
const tradePriceTotal = ref(0);
// 零售价合计
const retailPriceTotal = ref(0);
// 表单校验
const rules = ref({
  tradePrice: [{required: true, validator: tradePriceV, trigger: "change"}],
  retailPrice: [{required: true, validator: retailPriceV, trigger: "change"}],
  produceDate: [{required: true, message: "生产日期不能为空", trigger: "blur"}],
  expireDate: [{required: true, message: "有效期不能为空", trigger: "blur"}],
  batchNo: [{required: true, message: "批号不能为空", trigger: "blur"}],
  importClass: [{required: true, message: "入库方式不能为空", trigger: "change"}],
  discount: [{required: true, message: "比例不能为空", trigger: "change"}],
  // supplier: [
  //     {required: true, message: "供货单位不能为空", trigger: "blur"}
  // ],
  // storageFrom: [
  //     {required: true, message: "供货单位不能为空", trigger: "blur"}
  // ],
  storageId: [{required: true, message: "入库科室不能为空", trigger: "blur"}],
  quantity: [{required: true, validator: quantityNumber, trigger: "blur"}],
});
// const pickerOptions = ref({
//     disabledDate(time, lastDate) {
//         return time.getTime() < lastDate - 8.64e7;
//     }
// })

if (userInfo.orgId) {
  queryParams.value.orgId = userInfo.orgId;
}
if (!currentSelectDept) {
  // isImport.value = false;
  ElMessage.error("请选择库存药房后，再进行入库操作。");
} else {
  isImport.value = true;
  form.value.storageId = currentSelectDept;
  // getStoreroomDistinguishFun();
}

/**
 * 入库方式
 */
function importClassClick(value: string) {
  form.value.storageFrom = currentSelectDept
  const index = typeList.value.findIndex((item: any) => {
    return item.dictValue == value;
  });
  if (index > -1) {
    drugFromLevelStr.value = typeList.value[index].fromLevel + ","
  }
}

/**
 * 弹出入库发票号弹出框
 */
function importInvoiceElMessageBox() {
  if (!form.value.invoiceNo && currentSelectDept) {
    // 最终提交
    ElMessageBox.prompt('入库发票号', '请填写入库发票号', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      inputPattern: /^\S+$/,
      inputErrorMessage: '发票号不能为空',
      closeOnClickModal: false,
      closeOnPressEscape: false,
      showClose: false,
      showCancelButton: false,
    }).then(({value}) => {
      form.value.invoiceNo = value
    }).catch(() => {
      form.value.invoiceNo = ""
      ElMessage.info("已取消操作");
    });
  }
}

/** 项目名称自动补全检索 */
function itemNameInput(event, _value) {
  form.value.itemName = event;
  getAutoDrugPriceInfoFun();
}

/** 入库药品检索 */
function getAutoDrugPriceInfoFun() {
  const param = {
    storageId: form.value.storageFrom || currentSelectDept,
    orgId: queryParams.value.orgId,
    itemInfo: form.value.itemName,
  };
  getAutoDrugPriceInfo(param).then((res) => {
    tableBodyList.value = res.data;
    itemAutomatic.value.init();
  });
}

/** 药品自动补全点击事件 */
function rowClick(obj, index) {
  nextTick(() => {
    if (obj) {
      form.value.detailList[index].isShow = true
      form.value.detailList[index].itemInfo = obj.drugName;
      form.value.detailList[index].drugInfoId = obj.drugInfoId;
      form.value.detailList[index].drugName = obj.drugName;
      form.value.detailList[index].drugCode = obj.drugCode;
      form.value.detailList[index].orgId = obj.orgId;
      form.value.detailList[index].packageSpec = obj.packageSpec;
      form.value.detailList[index].currentSpec = obj.currentSpec;
      form.value.detailList[index].currentUnits = obj.currentUnits;
      form.value.detailList[index].packageUnits = obj.packageUnits;
      form.value.detailList[index].units = obj.units;
      form.value.detailList[index].tradePrice = obj.tradePrice;
      form.value.detailList[index].tradePriceShow = obj.tradePrice;
      form.value.detailList[index].retailPriceShow = obj.retailPrice;
      form.value.detailList[index].retailPrice = obj.retailPrice;
      form.value.detailList[index].packSize = obj.packSize;
      form.value.detailList[index].discount = "1";
      form.value.detailList[index].firmId = obj.firmId;
      form.value.detailList[index].firmName = obj.firmName;
      form.value.detailList[index].packageNum = obj.packageNum;
      form.value.detailList[index].drugPriceId = obj.drugPriceId;
      itemAutomatic.value.closePopover();
      itemAutomatic.value.itemNameFocus();
    }
  });
}

/**
 * 自动补全上边input获得焦点事件   待测试
 * @param _index
 * @param row
 */
function isShowItemNameFocus(_index: number, row: any) {
  row.isShow = false
  nextTick(() => {
    itemAutomatic.value.init()
    itemAutomatic.value.setItemName(row.drugName)
    itemAutomatic.value.focusInput()
  })
}


/** 生产日期校验 */
function disabledProduceDateFunc(time) {
  return time.getTime() > Date.now();
}

/** 有效期校验 */
// function disabledExpireDateFunc(time) {

// }

/** 生产日期点击事件 */
function produceDateChange(index) {
  //1095  三年
  const newDate = proxy.$addDay(1095, new Date(form.value.detailList[index].produceDate));
  if (newDate) {
    form.value.detailList[index].expireDate = proxy.$parseTime(newDate, "{y}-{m}-{d}");
  }
  if (
    proxy.$getDaysDiff(
      form.value.detailList[index].expireDate,
      new Date(form.value.detailList[index].produceDate)
    ) < 90
  ) {
    return ElMessage.error("药品有效期小于90天。");
  }
}

/** 有效期点击事件 */
function expireDateChange(index) {
  if (
    proxy.$getDaysDiff(
      form.value.detailList[index].expireDate,
      new Date(form.value.detailList[index].produceDate)
    ) < 90
  ) {
    return ElMessage.error("药品有效期小于90天。");
  }
}

/** 供货商点击事件 */
function supplierChange(obj) {
  form.value.supplier = obj.id;
  form.value.storageFrom = undefined;
}

/** 供应商选择事件 */
function storageFromClick(obj) {
  form.value.storageFrom = obj.storageId;
  form.value.supplier = undefined;
}

function storageIdClick(obj) {
  form.value.storageId = obj.storageId || obj.id;
}

// 监控科室是否改变，并查询入库方式
watch(() => currentSelectDept, () => {
  getStoreroomDistinguishFun()

}, {deep: true, immediate: true})

/** 根据科室id 出入库类型获取库房对应的出入库方式 */
function getStoreroomDistinguishFun() {
  if (currentSelectDept) {
    typeList.value = [];
    let param = {
      storageCode: currentSelectDept,
      orgId: queryParams.value.orgId,
      inoutType: "1",
      dictType: "drug_storage_type",
    };
    getStoreroomDistinguish(param).then((res: any) => {
      res.data.forEach((item: any) => {
        item.sysDictData.fromLevel = item.fromLevel
        typeList.value.push(item.sysDictData);
      });
      // 判断默认库房是 药库类型 ，如果是默认供货单位为 “供应商”
      if (res.data[0].storageType === "1") {
        form.value.importClass = "0";
      }
    });
  }
}

/** 查询药品入库暂存列表 */
function getList() {
  selectPageDrugImportMaster(queryParams.value).then((response: any) => {
    stagingList.value = response.rows;
    total.value = response.total;
  });
}

async function getListDetail() {
  await listDrugImportDetail(detailQuery.value).then((response: any) => {
    stagingListDetail.value = response.data;
    stagingListDetail.value.forEach((item: any) => {
      item.tradePriceShow = item.packSize === "1" ? item.tradePriceMin : item.tradePrice;
      item.retailPriceShow = item.packSize === "1" ? item.retailPriceMin : item.retailPrice;
    })
  });
  return stagingListDetail.value;
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: undefined,
    documentNo: undefined,
    storageId: undefined,
    importDate: undefined,
    supplier: undefined,
    storageFrom: undefined,
    accountReceivable: undefined,
    accountPayed: undefined,
    additionalFee: undefined,
    importClass: undefined,
    accountType: undefined,
    accountIndicator: undefined,
    acctDate: undefined,
    acctOperator: undefined,
    tally: undefined,
    tallyDate: undefined,
    tallyOperator: undefined,
    orgId: undefined,
    voucherNo: undefined,
    recoveryDocuNo: undefined,
    delFlag: undefined,
    createBy: undefined,
    createTime: undefined,
    updateBy: undefined,
    updateTime: undefined,
    remarks: undefined,
  };
}

function temporaryStorageClose() {
  // 暂存列表
  stagingList.value = [];
  // 暂存入库明细列表
  stagingListDetail.value = [];
  open.value = false;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  handleQuery();
}

/**
 * 暂存列表 引入
 * @param row
 */
async function bringIn(row) {
  if (form.value.detailListSave.length > 0) {
    return ElMessage.error("已添加列表存在未保存的数据，请暂存或者入库后再引入当前数据");
  }
  detailQuery.value.masterId = row.id;
  let stagingListDetail = await getListDetail();
  form.value.importClass = row.importClass;
  form.value.isStaging = row.isStaging;
  form.value.accountType = row.accountType;
  form.value.invoiceNo = row.invoiceNo;
  form.value.documentNo = row.documentNo;
  form.value.id = row.id;
  // 设置入库科室
  nextTick(() => {
    storageIdDeptRef.value.setValue(row.storageId);
  });
  // 设置供货单位
  if (row.importClass === "0") {
    form.value.supplier = row.supplier;
  } else {
    nextTick(() => {
      importClassClick(row.importClass)
      drugStorageDeptRef.value.setValue(row.storageFrom);
      form.value.storageFrom = row.storageFrom;
      form.value.storageId = row.storageId;
    });
  }
  // 设置入库明细
  stagingListDetail.forEach((obj) => {
    let detail: any = {};
    detail.itemInfo = obj.drugName;
    detail.id = obj.id;
    detail.drugInfoId = obj.drugInfoId;
    detail.masterId = obj.masterId;
    detail.drugName = obj.drugName;
    detail.drugCode = obj.drugCode;
    detail.orgId = obj.orgId;
    detail.packageSpec = obj.packageSpec;
    detail.currentSpec = obj.packageSpec;
    detail.packageUnits = obj.packageUnits;
    detail.currentUnits = obj.packSize === "1" ? obj.minUnits : obj.packageUnits;
    detail.tradePrice = obj.tradePrice;
    detail.tradePriceMin = obj.tradePriceMin;
    detail.tradePriceShow = obj.packSize === "1" ? obj.tradePriceMin : obj.tradePrice;
    detail.discount = obj.discount;
    detail.retailPrice = obj.retailPrice;
    detail.retailPriceMin = obj.retailPriceMin;
    detail.retailPriceShow = obj.packSize === "1" ? obj.retailPriceMin : obj.retailPrice;
    detail.packageNum = obj.packageNum;
    detail.drugPriceId = obj.drugPriceId;
    detail.packSize = obj.packSize;
    // packSize === '1' 小包装  packSize === '2' 大包装
    detail.quantity = obj.quantity;
    detail.produceDate = obj.produceDate;
    detail.expireDate = obj.expireDate;
    detail.batchNo = obj.batchNo;
    detail.location = obj.location;
    detail.firmName = obj.firmName;
    detail.firmId = obj.firmId;
    detail.drugPriceId = obj.priceId;
    detail.supplier = form.value.supplier
    detail.trackCodes = obj.trackCodes
    form.value.detailListSave.push(detail);
  });
  computeSum();
  open.value = false;
}

/** 已开药品明细计算合计 */
function computeSum() {
  // 进价合计
  let tradePriceTotalThis: number = 0;
  // 零售价合计
  let retailPriceTotalThis: number = 0;
  form.value.detailListSave.forEach((item: any) => {
    let quantity = item.quantity;
    let tradePriceThis = 0.00
    let retailPriceThis = 0.00
    // if (item.packSize === "2") {
    //   tradePriceThis = item.tradePrice
    //   retailPriceThis = item.retailPrice
    // } else {
    //   tradePriceThis = item.tradePriceMin
    //   retailPriceThis = item.retailPriceMin
    // }
    tradePriceTotalThis += Number(item.retailPriceShow) * quantity;
    retailPriceTotalThis += Number(item.retailPriceShow) * quantity;
  });
  // 进价合计
  tradePriceTotal.value = Number(tradePriceTotalThis.toFixed(2));
  // 零售价合计
  retailPriceTotal.value = Number(retailPriceTotalThis.toFixed(2));
}

/** 暂存列表主记录点击事件 */
async function stagingMaster(row, _index) {
  detailQuery.value.masterId = row.id;
  await getListDetail();
}

/** 新增按钮操作 */
function handleAdd(row: any) {
  if (!form.value.importClass) {
    return ElMessage.error("入库方式不能为空");
  }
  if (!form.value.storageId) {
    return ElMessage.error("入库科室不能为空");
  }
  if (form.value.importClass === "0" && !form.value.supplier) {
    return ElMessage.error("供货单位不能为空");
  }
  if (form.value.importClass !== "0" && !form.value.storageFrom) {
    return ElMessage.error("供货单位不能为空");
  }
  if (row.trackCodes) {
    // 分割字符串并过滤空值
    const trackCodesArray = row.trackCodes.replace(/\n/g, '').split(';').filter(code => code.trim() !== '');
    // 统计每个追溯码出现的次数 返回一个对象，键为追溯码，值为出现次数
    const trackCodesCount = trackCodesArray.reduce((acc, code) => {
      acc[code] = (acc[code] || 0) + 1;
      return acc;
    }, {} as Record<string, number>);
    const result: string[] = [];
    // 遍历对象，找出出现次数大于1的追溯码，返回一个数组
    for (const key in trackCodesCount) {
      if (trackCodesCount.hasOwnProperty(key) && trackCodesCount[key] > 1) {
        result.push(key);
      }
    }
    if (result.length > 0) {
      ElMessage.error(`追溯码${result.join('、')}重复，不能添加到已编辑列表，请检查！`);
      return false;

    }
  }
  // form.detailList.push({discount: '1', retailPrice: ''})
  (formRef.value as any).validate((valid) => {
    // importInvoiceElMessageBox()
    if (valid) {
      if (form.value.detailList[0].packSize === '2') {
        form.value.detailList[0].retailPriceMin = (form.value.detailList[0].retailPriceShow / form.value.detailList[0].packageNum).toFixed(4)
        form.value.detailList[0].tradePriceMin = (form.value.detailList[0].tradePriceShow / form.value.detailList[0].packageNum).toFixed(4)
      } else {
        form.value.detailList[0].retailPriceMin = form.value.detailList[0].retailPriceShow
        form.value.detailList[0].tradePriceMin = form.value.detailList[0].tradePriceShow
        form.value.detailList[0].retailPrice = (form.value.detailList[0].retailPriceShow * form.value.detailList[0].packageNum).toFixed(2)
        form.value.detailList[0].tradePrice = (form.value.detailList[0].tradePriceShow * form.value.detailList[0].packageNum).toFixed(2)
      }
      // 添加到已编辑列表
      form.value.detailListSave.push(form.value.detailList[0]);
      // 删除当前编辑列表数据
      form.value.detailList = [{expireDate: "", discount: "1"}];
      nextTick(() => {
        itemAutomatic.value.setItemName("");
      });
      computeSum();
      //清空追溯码弹出框input内容
      trackCodesInput.value = ""
    }
  });
  tableBodyList.value = [];
}

/** 进价焦点消失 、计算售价*/
function tradePriceBlue(index) {
  // 进价
  let tradePrice = form.value.detailList[index].tradePriceShow;
  form.value.detailList[index].tradePrice = form.value.detailList[index].tradePriceShow
  if (tradePrice) {
    // 获取点击行的行号index
    const ratioIndex = dictDataMap.value["price_ratio"].findIndex((item) => {
      return item.dictValue === form.value.detailList[index].discount;
    });
    if (ratioIndex > -1) {
      // 设置本行售价
      form.value.detailList[index].retailPrice = (
        tradePrice * Number(dictDataMap.value["price_ratio"][ratioIndex].dictLabel)
      ).toFixed(4);
      form.value.detailList[index].retailPriceShow = form.value.detailList[index].retailPrice
      form.value.detailList[index].retailPriceShow = form.value.detailList[index].retailPrice
    }
  }
}

/** 修改按钮操作 */
function handleUpdate(row, index) {
  if (form.value.detailList[0].itemInfo) {
    ElMessageBox.confirm(
      "编辑列表存在未保存的药品数据，继续编辑将会替换编辑列表中的数据，确定要继续嘛？",
      "提示",
      {
        confirmButtonText: "替换编辑",
        cancelButtonText: "取消",
        type: "warning",
      }
    )
      .then(() => {
        form.value.detailList = [{expireDate: "", discount: "1"}];
        form.value.detailList[0] = row;
        form.value.detailListSave.splice(index, 1);
        nextTick(() => {
          itemAutomatic.value.setItemName(row.drugName);
        });
      })
      .catch(() => {
      });
  } else {
    form.value.detailList = [{expireDate: "", discount: "1"}];
    console.log("row", row)
    form.value.detailList[0] = row;
    form.value.detailListSave.splice(index, 1);
    nextTick(() => {
      itemAutomatic.value.setItemName(row.drugName);
    });
  }
}

/** 暂存 */
function temporaryStorage() {
  form.value.isStaging = "Y";
  save();
}

/** 最终提交 */
function lastSave() {
  form.value.isStaging = "N";
  save();
}

function save() {
  if (form.value.detailListSave.length <= 0) {
    return ElMessage.error("没有需要入库的药品明细，不能提交");
  }
  // if (!form.value.invoiceNo) {
  //   return ElMessage.error("入库收据号为空，不能提交");
  // }
  ElMessageBox.confirm(
    `${form.value.isStaging === "Y" ? "确认要进行暂存吗？" : "确认要进行入库吗？"}`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      form.value.orgId = queryParams.value.orgId;
      form.value.accountReceivable = tradePriceTotal.value;
      form.value.accountPayed = tradePriceTotal.value;
      buttonLoading.value = true;
      let i = 0;
      form.value.detailListSave.forEach((item: any) => {
        i++;
        item.produceDate = proxy.$parseTime(item.produceDate, "{y}-{m}-{d} {h}:{i}:{s}");
        item.expireDate = proxy.$parseTime(item.expireDate, "{y}-{m}-{d} {h}:{i}:{s}");
        item.itemNo = i;
      });
      buttonLoading.value = true;
      addDrugImportMaster(form.value).then(() => {
        // 清空入库发票号
        form.value.invoiceNo = ""
        if (form.value.isStaging === "Y") {
          ElMessage.success("暂存成功");
        } else {
          ElMessage.success("入库成功");
        }
        form.value.detailListSave = [];
        form.value.id = ''
        retailPriceTotal.value = 0.00
        tradePriceTotal.value = 0.00
      })
        .finally(() => {
          buttonLoading.value = false;
        });
    })
    .catch(() => {
      ElMessage.info("已取消操作");
    });
}

/** 暂存列表弹出框 */
function temporaryStorageTableClick() {
  open.value = true;
  queryParams.value.isStaging = "Y";
  getList();
}

/** 删除按钮操作 */
function handleDelete(row, index) {
  // const ids = row.id || ids;
  ElMessageBox.confirm('是否确认删除药品"' + row.drugName + '"的数据？', {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      form.value.detailListSave.splice(index, 1);
      ElMessage.success("删除成功");
    })
    .catch(() => {
    });
}

/**
 * 追溯码录入
 */
function trackCodesEnter(row: any, index: number) {
  trackCodesInput.value = row.trackCodes
  trackCodesEnterOpen.value = true
  currentIndex.value = index
  trackCodesRow.value = row
}

/**
 * 追溯码录入框关闭
 */
function trackCodesCancel() {
  trackCodesInput.value = ""
  trackCodesEnterOpen.value = false
  currentIndex.value = -1
}

/**
 * 追溯码录入框确定按钮
 */
function trackCodesOk() {
  form.value.detailList[currentIndex.value].trackCodes = trackCodesInput.value
  trackCodesCancel()
}

/**
 * 追溯码录入页面input回车事件
 */
function lineFeed() {
  if (trackCodesInput.value[trackCodesInput.value.length - 1] != ";") {
    trackCodesInput.value += ";"
  }
}

function deleteMaster(row: any) {
  ElMessageBox.confirm('是否确认删除暂存数据？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    delDrugImportMaster(row.id).then(() => {
      getList();
      stagingListDetail.value = []
      ElMessage.success("删除成功");
    })
  })
}

</script>

<script lang="ts">
export default {
  name: "DrugImportMaster"
}
</script>

<style scoped>
:deep(.el-top) {
  background-color: rgb(212, 211, 211);
  border-radius: 5px 5px 5px 5px;
  margin: -5px 3px 5px 3px;
  height: 44px;
}

:deep(.dept-tree-label) {
  margin-right: -77px;
  margin-top: 6px;
  width: 18%;
}

:deep(.vue-treeselect__input-container) {
  height: 26px !important;
}

.account_type {
  font-weight: bold;
  color: rgb(30, 30, 30);
  float: left;
  width: 6%;
  /*margin-top: 6px;*/
}

:deep(.cell .el-tag) {
  margin: 0 -10px 0 -10px;
}

:deep(.el-input__wrapper) {
  background-color: #ff000017;
}

</style>
